package com.tju.resource.oauth.controller.tb;

import cn.hutool.json.JSONObject;
import com.tju.resource.annotation.Log;
import com.tju.resource.business.tb_outward.report.TbOWReportService;
import com.tju.resource.tool.enum_utils.FunctionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
public class TbOWReportController {

    private static final String prefix = "owrepo";

    @Autowired
    TbOWReportService tbOWReportService;

    @PostMapping(prefix + "/export")
    @PreAuthorize("hasAuthority('sys:goods:oward:export')")
    @Log(type= FunctionType.Export)
    public void export(@RequestBody JSONObject params, HttpServletResponse response) {
        OutputStream out = null;
        try {
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("OutWard" + Math.random() + ".xls", StandardCharsets.UTF_8));

            out = response.getOutputStream();
            boolean export = tbOWReportService.export(params, out);

            if (!export) {
                throw new Exception("Unknown error!");
            }

        } catch (Exception e) {
            response.setStatus(500);
            e.printStackTrace();

            if (null != out) {
                try {
                    out.write(e.toString().getBytes());
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        } finally {
            if (null != out) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
